<script setup lang="ts">
import { useAppsStore } from '@/stores/modules/app'
import EmjoyList from '@/views/detail/components/EmjoyList.vue'
import CommentNav from '@/views/detail/components/comment/comment-nav.vue'
import UserNav from '@/views/detail/components/user/user-nav.vue'
import ReplyUser from '@/views/detail/components/user/reply-user.vue'
import TagsNav from '@/views/detail/components/tags/tags-nav.vue'
import WorksList from '@/views/detail/components/user/work-list.vue'
import CommentList from '@/views/detail/components/comment/comment-list.vue'
import commentApi from '@/service/api/comment'
import detailApi from '@/service/api/detail'
import type { infoItem } from '@/types/page/img'
import ZjList from '@/views/detail/components/comment/ZjList.vue'
type PropsState = {
  replyInfo: any
  chapterIndex: number
  chapterList: any[]
}
withDefaults(defineProps<PropsState>(), {
  chapterIndex: -1,
  replyInfo: () => {
    return {}
  },
  chapterList: () => {
    return []
  }
})
const useStore = useAppsStore()
const { getUserInfo: userInfo } = storeToRefs(useStore)
const emit = defineEmits(['close', 'check', 'follow', 'change'])
const chapterChange = (e: number) => {
  emit('change', e)
  close()
}
const followChange = () => {
  emit('follow')
}
const handCheck = (e: any) => {
  emit('check', e)
  emit('close')
  close()
}
const commentRef = ref()
const info = ref<infoItem>({
  tags: []
})
const imgInfo = ref<any>({})
const currenChange = (e: number) => {
  state.curren = e
  bottom = false
}

const state = reactive({
  show: false,
  curren: 1,
  replyName: '',
  content: '',
  showEmjjoy: false
})

const handSubmit = async () => {
  if (!state.content) {
    msgUtil.$message.error(
      state.replyName ? '请输入回复内容' : '请输入评论内容'
    )
    return
  }
  if (state.replyName) {
    const params = {
      id: commentState.id,
      content: state.content,
      isMore: commentState.isMore
    }
    const { code, data, msg } = await commentApi.reply(params)
    if (code !== 0) {
      msgUtil.$message.error(msg)
      return
    }
    removeReply()
    state.content = ''
    commentRef.value?.replyPush(data)
  } else {
    const params = {
      exchangeId: info.value.id,
      imageId: imgInfo.value.id,
      content: state.content,
      type: 4
    }
    const { code, msg } = await commentApi.comments(params)
    if (code !== 0) {
      msgUtil.$message.error(msg)
      return
    }
    removeReply()
    state.content = ''
    commentRef.value?.onRefresh()
  }
}
/**
 * 评论|| 回复
 * */
const commentState = {
  id: 0,
  isMore: false
}
const removeReply = () => {
  state.replyName = ''
  commentState.id = 0
  commentState.isMore = false
}
const handReply = (e: any) => {
  commentState.id = e.id
  commentState.isMore = e.isMore
  state.replyName = `${e.userInfo.nickname}: ${e.content}`
  state.content = ''
  nextTick(() => {
    inputRef.value?.focus()
  })
}

/**
 * 输入框
 * */
const inputRef = ref()
const textareaRef = ref()
const inputChange = (event: Event) => {
  const input = event.target as HTMLInputElement
  if (input.value.length > 10) {
    nextTick(() => {
      textareaRef.value?.focus()
    })
  }
}

const adjustTextareaHeight = (event: Event) => {
  const textarea = event.target as HTMLTextAreaElement
  textarea.style.height = 'auto'
  textarea.style.height = `${textarea.scrollHeight}px`
  if (textarea.value.length <= 10) {
    nextTick(() => {
      inputRef.value?.focus()
    })
  }
}

/**
 * 表情
 * */
const emjoyOut = () => {
  state.showEmjjoy = false
}
const insertAtCursor = (input: HTMLInputElement, text: string) => {
  const start = input.selectionStart || 0
  const end = input.selectionEnd || 0
  state.content =
    input.value.substring(0, start) + text + input.value.substring(end)
  input.value =
    input.value.substring(0, start) + text + input.value.substring(end)
  input.selectionStart = input.selectionEnd = start + text.length
  input.focus()
  state.showEmjjoy = false
}
const selectEmoji = (emoji: string) => {
  if (state.content.length > 10) {
    insertAtCursor(textareaRef.value, emoji)
  } else {
    insertAtCursor(inputRef.value, emoji)
  }
}
const workRef = ref()
const replyRef = ref()
const tagRef = ref()
const init = () => {
  workRef.value?.init()
  tagRef.value?.init()
  replyRef.value?.init()
}
/**
 * 页面滚动
 * */
let bottom = false
const scrollChange = (e: Event) => {
  const target = e.target as HTMLElement
  if (target.scrollHeight - (target.scrollTop + target.clientHeight) <= 200) {
    if (bottom) return
    bottom = true
    if (state.curren === 0) {
      workRef.value?.onBottom(() => {
        bottom = false
      })
    } else if (state.curren === 3) {
      replyRef.value?.onBottom(() => {
        bottom = false
      })
    } else if (state.curren === 1) {
      commentRef.value?.onBottom(() => {
        bottom = false
      })
    } else {
      setTimeout(() => {
        bottom = false
      }, 2000)
    }
  }
}
const authUser = ref<any>({})
const getUser = async () => {
  if (info.value.author_id) {
    const { data } = await detailApi.user(info.value.author_id)
    authUser.value = data
  }
}
const open = async (e: infoItem, currenImg: any, current?: number) => {
  state.content = ''
  state.replyName = ''
  info.value = e
  await getUser()
  imgInfo.value = currenImg
  state.show = true
  if (current) {
    state.curren = current
  } else {
    state.curren = 1
  }
  nextTick(() => {
    init()
  })
}
const close = () => {
  state.show = false
}
const showChange = (e: boolean) => {
  if (!e) {
    emit('close')
  }
  state.show = e
}

function IsPhone() {
  var info = navigator.userAgent
  return /mobile/i.test(info)
}
defineExpose({
  open
})
</script>

<template>
  <div>
    <n-drawer
      v-model:show="state.show"
      :width="IsPhone() ? '100%' : '400px'"
      height="100%"
      style="
        --n-color: rgba(0, 0, 0, 0.3);
        --n-header-border-bottom: 2px solid rgba(255, 255, 255, 0);
        --n-footer-border-top: 1px solid rgba(255, 255, 255, 0);
        --n-text-color: #fff;
        --n-header-padding: 0;
        --n-body-padding: 0;
      "
      :style="{
        '--n-color': IsPhone() ? 'rgba(0, 0, 0, 1)' : 'rgba(0, 0, 0, 0.3)'
      }"
      :placement="IsPhone() ? 'bottom' : 'right'"
      @update-show="showChange"
    >
      <n-drawer-content
        :native-scrollbar="false"
        :scrollbar-props="{
          size: 1,
          onScroll: scrollChange
        }"
      >
        <template #header>
          <div class="header">
            <div class="header-top flex align-center flex-between">
              <div class="tabs flex align-center">
                <div
                  class="tab"
                  v-if="chapterList.length > 0"
                  :class="{ 'tab-active': state.curren === 4 }"
                  @click="currenChange(4)"
                >
                  目录
                </div>
                <div
                  class="tab"
                  :class="{ 'tab-active': state.curren === 0 }"
                  @click="currenChange(0)"
                >
                  角色
                </div>
                <div
                  class="tab"
                  :class="{ 'tab-active': state.curren === 1 }"
                  @click="currenChange(1)"
                >
                  评论
                </div>
                <div
                  class="tab"
                  :class="{ 'tab-active': state.curren === 3 }"
                  @click="currenChange(3)"
                >
                  TA的发布
                </div>
                <div
                  class="tab"
                  :class="{ 'tab-active': state.curren === 2 }"
                  @click="currenChange(2)"
                >
                  关联标签
                </div>
              </div>
              <div class="close" @click="showChange(false)">
                <i class="esayIcon esayIcon-guanbi"></i>
              </div>
            </div>
            <user-nav v-show="state.curren === 0" :user="authUser" />
            <reply-user
              v-show="state.curren === 3"
              :user="replyInfo"
              @follow="followChange"
              @close="showChange(false)"
            />
            <comment-nav
              v-show="state.curren === 1"
              :commentCount="info.commentCount"
            />
            <tags-nav v-show="state.curren === 2" :list="info.tags" />
          </div>
        </template>
        <div class="comment-main">
          <div v-if="state.curren === 4">
            <zj-list
              :list="chapterList"
              :chapterIndex="chapterIndex"
              @change="chapterChange"
            />
          </div>
          <div v-show="state.curren === 0">
            <works-list
              ref="workRef"
              :authorId="info.author_id"
              @check="handCheck"
            />
          </div>
          <div v-show="state.curren === 3">
            <works-list
              ref="replyRef"
              :releaseid="info.releaseid"
              @check="handCheck"
            />
          </div>
          <div v-show="state.curren === 1">
            <comment-list
              ref="commentRef"
              :photoId="info.id"
              @reply="handReply"
            />
          </div>
          <div v-show="state.curren === 2">
            <template v-if="info.tags && info.tags.length === 0">
              <div class="empty">
                <span>暂无标签</span>
              </div>
            </template>
            <template v-else>
              <works-list ref="tagRef" :tags="info.tags" @check="handCheck" />
            </template>
          </div>
        </div>
        <template #footer>
          <template v-if="state.curren === 1">
            <template v-if="userInfo.id">
              <div class="drawer-bottom">
                <div class="reply-row" v-if="state.replyName">
                  <div class="name u-line-1">回复@{{ state.replyName }}</div>
                  <div class="close" @click="removeReply">
                    <i class="esayIcon esayIcon-guanbi"></i>
                  </div>
                </div>
                <n-popover
                  :animated="false"
                  :overlap="false"
                  :show-arrow="false"
                  :show="state.showEmjjoy"
                  width="trigger"
                  placement="top-end"
                  trigger="manual"
                  style="
                    --n-color: #252632;
                    --n-text-color: #fff;
                    --n-space: -5px;
                    --n-border-radius: 3px 3px 0 0;
                    --n-padding: 6px;
                  "
                  @clickoutside="emjoyOut"
                >
                  <template #trigger>
                    <div
                      class="diy-input"
                      :class="{
                        'diy-input-reply': !!state.replyName,
                        'diy-input-more': state.content.length > 10
                      }"
                    >
                      <template v-if="state.content.length > 10">
                        <textarea
                          v-model="state.content"
                          @input="adjustTextareaHeight"
                          ref="textareaRef"
                          :placeholder="
                            state.replyName
                              ? '请输入回复内容...'
                              : '留下您的精彩评论吧!'
                          "
                        />
                      </template>
                      <template v-else>
                        <input
                          v-model="state.content"
                          type="text"
                          ref="inputRef"
                          :placeholder="
                            state.replyName
                              ? '请输入回复内容...'
                              : '留下您的精彩评论吧!'
                          "
                          @input="inputChange"
                        />
                      </template>
                      <div class="tool">
                        <div class="icon" @click="state.showEmjjoy = true">
                          <i class="esayIcon esayIcon-biaoqing"></i>
                        </div>
                        <div
                          class="icon submit-icon"
                          v-if="state.content"
                          @click="handSubmit"
                        >
                          <i class="esayIcon esayIcon-xiangshang"></i>
                        </div>
                      </div>
                    </div>
                  </template>
                  <emjoy-list @emojiSelected="selectEmoji" />
                </n-popover>
              </div>
            </template>
            <template v-else>
              <div class="footer-input">
                <span>请先</span>
                <span class="login-text">登录</span>
                <span>后发表评论</span>
              </div>
            </template>
          </template>
        </template>
      </n-drawer-content>
    </n-drawer>
  </div>
</template>

<style scoped lang="scss">
.header {
  color: rgba(255, 255, 255, 0.7);
  text-shadow: rgba(0, 0, 0, 0.2) 0px 1px 1px;
  width: 100%;

  .header-top {
    border-bottom: 2px solid rgba(255, 255, 255, 0.06);
    padding: 0 10px;

    .tabs {
      .tab {
        font-size: 14px;
        margin-right: 15px;
        cursor: pointer;
        opacity: 0.6;
        position: relative;
        padding: 15px 0;

        &:before {
          content: '';
          display: block;
          position: absolute;
          left: 0;
          bottom: 0;
          width: 100%;
          height: 3px;
          background-color: rgba(255, 255, 255, 0);
          transition: background-color 0.2s;
          border-radius: 3px;
        }

        &:hover {
          opacity: 1;

          &:before {
            background-color: rgba(255, 255, 255, 0.2);
          }
        }

        &-active {
          opacity: 1;

          &:before {
            background-color: #ff0033;
          }

          &:hover {
            &:before {
              background-color: #ff0033;
            }
          }
        }
      }
    }
  }

  .close {
    cursor: pointer;
    color: #fff;
    opacity: 0.6;

    i {
      font-weight: bold;
    }

    &:hover {
      opacity: 1;
    }
  }
}

.comment-main {
  padding: 0 10px;
}

.drawer-bottom {
  width: 100%;

  .reply-row {
    display: flex;
    align-items: center;
    padding: 8px;
    background-color: rgba(0, 0, 0, 0.4);
    border-radius: 12px 12px 0 0;

    .name {
      flex: 1 0 0;
      width: 0;
      font-size: 12px;
      color: rgba(255, 255, 255, 0.4);
    }

    .close {
      cursor: pointer;
      margin-left: 10px;
      width: 15px;
      height: 15px;
      border-radius: 50%;
      background-color: rgba(255, 255, 255, 0.6);
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;

      i {
        font-weight: bold;
        font-size: 9px;
        color: #333;
      }

      &:hover {
        background-color: rgba(255, 255, 255, 1);
      }
    }
  }
}

.emjoy-pop {
  position: absolute;
  bottom: 0;
  height: 200px;
  background-color: red;
}

.diy-input {
  width: 100%;
  background-color: rgba(255, 255, 255, 0.2);
  border: unset !important;
  height: 40px;
  cursor: pointer;
  border-radius: 7px;
  align-items: center;
  display: flex;
  overflow: hidden;
  padding: 3px 10px;

  &-reply {
    border-radius: 0 0 7px 7px;
  }

  textarea {
    margin-top: 5px;
    width: 100%;
    background: transparent;
    border-style: none;
    color: #eee;
    overflow: hidden;
    resize: none;
    font-size: 14px;
  }

  input {
    flex: 1;
    height: 40px;
    background-color: rgba(255, 255, 255, 0);
    outline: none;
    border: none;
    color: #eee;
    font-size: 14px;
  }

  .tool {
    display: flex;
    align-items: center;
    justify-content: flex-end;

    .icon {
      width: 23px;
      height: 23px;
      margin-left: 10px;
      display: flex;
      align-items: center;
      justify-content: center;

      i {
        font-size: 19px;
      }
    }

    .submit-icon {
      background-color: #fe2c55;
      border-radius: 50%;

      i {
        font-size: 14px;
        font-weight: bold;
        position: relative;
        bottom: 1px;
      }
    }
  }

  &-more {
    display: block;
    height: auto;
    padding: 7px 10px 8px 10px;
  }
}

.empty {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-content: center;
  justify-content: center;
  padding: 20px;

  span {
    text-align: center;
  }
}

.footer-input {
  width: 100%;
  background-color: rgba(255, 255, 255, 0.2);
  border: unset !important;
  height: 44px;
  cursor: pointer;
  border-radius: 7px;
  justify-content: center;
  align-items: center;
  display: flex;

  span {
    font-size: 14px;
    color: rgba(255, 255, 255, 0.6);
  }

  .login-text {
    color: #ff0033 !important;
    padding: 0 4px;
  }
}
</style>
<style lang="scss">
.n-drawer-header__main {
  width: 100%;
}
</style>
